﻿#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);

    timerId = startTimer(30);
    bufferLen = 300;
    sinBuffer = new double[bufferLen];
    cosBuffer = new double[bufferLen];

    plot1 = new DynamicPlot("sin",sinBuffer,bufferLen,0.1,-1,bufferLen*0.1,-1,1);//创建plot对象
    plot2 = new DynamicPlot("cos",cosBuffer,bufferLen,0.1,-1,bufferLen*0.1,-1,1);

    QChartView *chartView;
    QGridLayout *layout;

    chartView = plot1->getChartView();          //获取plot的图表查看实例
    layout = new QGridLayout(ui->tabWidget_sin);//新建layout
    layout->addWidget(chartView,0,0);           //将图表查看实例放到新layout上

    chartView = plot2->getChartView();
    layout = new QGridLayout(ui->tabWidget_cos);
    layout->addWidget(chartView,0,0);


    freshChart();
}

Widget::~Widget()
{
    delete ui;
}

void Widget::freshChart()
{
    dataGenerater_sin(sinBuffer,bufferLen,0.1);//生成新的sin数组
    dataGenerater_cos(cosBuffer,bufferLen,0.1);
    plot1->freshPlot();     //刷新plot曲线
    plot2->freshPlot();
}

void Widget::timerEvent(QTimerEvent *event)
{
    if (event->timerId() == timerId) {
        freshChart();
    }
}

//用于不断生成sin曲线
void Widget::dataGenerater_sin(double *buffer, int bufferLen, double stepLen)
{
    static double x = 0.0;
    for(int i = bufferLen-1; i > 0; i--)
    {
        buffer[i] = buffer[i-1];
    }
    buffer[0] = sin(x);
    x += stepLen;
}

//用于不断生成cos曲线
void Widget::dataGenerater_cos(double *buffer, int bufferLen, double stepLen)
{
    static double x = 0.0;
    for(int i = bufferLen-1; i > 0; i--)
    {
        buffer[i] = buffer[i-1];
    }
    buffer[0] = cos(x);
    x += stepLen;
}
